// 添加一个标记点
async function addMarker(data){
  const { name, content, lineId, lineName, latitude, longitude, userId, serialNumber  } = data
  if (!name){
    return {code: 500, msg: '缺少名称', data: null}
  }else if( !lineId) {
    return {code: 500, msg: '缺少路线 Id', data: null}
  }else if (!latitude || !longitude) {
    return {code: 500, msg: '缺少经纬度', data: null}
  }else {
    const dateTime = global.commonFun.getNowTime()
    const addSqlParams = [name, content, lineId,lineName, latitude,longitude, userId,dateTime, dateTime, serialNumber];
    const str = `name,content,lineId,lineName,latitude,longitude,userId,createTime,updateTIme,serialNumber`
    const addStr = global.commonFun.addSqlStr(str)
    let addSql = `INSERT INTO marker(${str}) VALUES(${addStr})`
    const addRow = await global.sql(addSql,addSqlParams)
    if (addRow.status) {
      return {code: 200, msg: '添加成功', data: null}
    }else {
      return {code: 500, msg: '服务繁忙', data: null}
    }
  }
}

// 查询路线关联的全部 marker 点
async function getAllMarker(markerId){
  const markerArr = markerId.toString()
  const selectMarkerSql = `SELECT * FROM marker WHERE id IN(${markerArr}) `;
  return await global.sql(selectMarkerSql)
}

// 根据路线 Id 去查询全部标记
async function getMarkerListByLineId(lineId) {
  if (lineId) {
    // 按照serialNumber的升序来排序
    const selectSql =  `SELECT * FROM marker WHERE lineId = ${lineId} ORDER BY serialNumber `
    const selectRow = await global.sql(selectSql)
    if (selectRow.status) {
      return selectRow.data
    }else {
      return []
    }
  }else {
    console.log('缺少lineId')
    return []
  }
}

// 删除标记点
async function delMarker(id) {
  if (id) {
    let delMarkerSql = `DELETE FROM marker WHERE id = ${id}`
    let delStepSql = `DELETE FROM step WHERE originMarkerId = ${id} OR destinationMarkerId = ${id}`
    const arr = await Promise.all([global.sql(delMarkerSql), global.sql(delStepSql)])
    const statusArr = arr.map(item => {
      return item.status
    })
    if (statusArr.includes(false)) {
      return {code: 500, msg: '服务器繁忙', data: null}
    }else {
      return {
        code: 200,
        msg: '删除成功',
        data: null
      }
    }
  }else {
    console.log('缺少lineId')
    return []
  }
}

exports.addMarker = addMarker
exports.getAllMarker = getAllMarker
exports.getMarkerListByLineId = getMarkerListByLineId
exports.delMarker = delMarker
